package com.ygsoft.activiti.controller;


import com.ygsoft.activiti.configuration.ActivitiConfiguration;
import com.ygsoft.activiti.eunm.ActivitProccessEnum;
import com.ygsoft.activiti.model.CompleteTask;
import com.ygsoft.activiti.model.MyModel;
import com.ygsoft.activiti.model.MyProcess;
import com.ygsoft.activiti.properties.ActivitiProperties;
import com.ygsoft.activiti.reposirory.CompleteTaskReposirory;
import com.ygsoft.activiti.service.RespositoryServiceInf;
import com.ygsoft.activiti.utils.PageUtils;
import com.ygsoft.activiti.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * activit
 *
 * @author zhx
 * @create 2017-11-20 9:23
 **/
@RestController
@RequestMapping("/activiti/model")
@Api(description = "activiti操作控制器")
public class RespositoryController {
    private Logger logger = LoggerFactory.getLogger(ActivitiConfiguration.class);

    @Autowired
    private RespositoryServiceInf respositoryService;

    @Autowired
    private CompleteTaskReposirory completeTaskReposirory;

    @Autowired
    private ActivitiProperties activitiProperties;



    /**
     * @param name        模型名称
     * @param key         模型key值
     * @param description 模型描述
     * @Date: 13:41
     * 创建模型功能
     */
    @PostMapping(value = "/create")
    @ResponseBody
    public R create(@RequestParam("name") String name,
                    @RequestParam("key") String key,
                    @RequestParam("description") String description) {
        try {
            String entrance = activitiProperties.getBower().getEntrance();
            if(StringUtils.isEmpty(entrance)){
                return R.error("流程设计URL未定义!请配置yglink.activiti.bower.entrance");
            }

            String model = respositoryService.createModel(name, key, description);

            return R.ok("创建模型成功!").put("data", entrance+"?modelId=" + model);
        } catch (Exception e) {
            logger.error("创建模型失败", e);
            return R.error("创建模型失败!");
        }
    }

    /**
     * 编辑模型
     */
    @PostMapping(value = "/edit")
    @ResponseBody
    public R edit(@RequestParam("modelId") String modelId) {
        try {
            String entrance = activitiProperties.getBower().getEntrance();
            if(StringUtils.isEmpty(entrance)){
                return R.error("流程设计URL未定义!请配置yglink.activiti.bower.entrance");
            }

            return R.ok().put("data", entrance+"?modelId=" + modelId);
        } catch (Exception e) {
            return R.error("创建模型失败!");
        }
    }


    /**
     * 获取模型列表
     */
    @PostMapping(value = "/getAllModels")
    @ResponseBody
    @ApiOperation(value = "获取模型列表", notes = "获取模型列表")
    public R getAllModels() {
        List<MyModel> allModule = respositoryService.getAllModule();

        PageUtils pageUtil = new PageUtils(allModule, 20, 1, 20);
        return R.ok().put("page", pageUtil);
    }

    /**
     * 部署模型
     */
    @PostMapping("/deployModel")
    @ResponseBody
    public R deployModel(@RequestParam("modelId") String modelId) throws UnsupportedEncodingException {
        boolean b = respositoryService.deployModel(modelId);
        return (b) ? R.ok() : R.error("部署失败");
    }


    /**
     * @Date: 13:48 2017/11/9
     * 根据制定模型Id、删除模型
     */
    @PostMapping("/deleteModel")
    @ResponseBody
    public R deleteModel(@RequestParam("modelId") String modelId) throws UnsupportedEncodingException {
        boolean b = respositoryService.deleteModel(modelId);
        return (b) ? R.ok() : R.error("删除失败,请查看是否此流程已部署!");
    }


    /**
     * 获取所有已经部署的流程列表
     */
    @PostMapping(value = "/getAllProcess")
    @ApiOperation(value = "获取所有已经部署的流程列表", notes = "获取所有已经部署的流程列表")
    @ResponseBody
    public R getAllProcess() {
        List<MyProcess> allProcess = respositoryService.getAllProcess();

        PageUtils pageUtil = new PageUtils(allProcess, 20, 1, 20);
        return R.ok().put("page", pageUtil);
    }

    /**
     * 删除部署流程
     */
    @PostMapping(value = "/deleteProcess")
    @ResponseBody
    public R deleteProcess(@RequestParam("processId") String processId) {
        boolean b = respositoryService.deleteDeployment(processId);
        return (b) ? R.ok() : R.error("删除失败!");
    }

    /**
     * 挂起部署流程
     */
    @PostMapping(value = "/changeProcessStatus")
    @ResponseBody
    public R changeProcessStatus(@RequestParam("processId") String processId) {
        int i = respositoryService.changeProcessStatus(processId);

        return R.ok("流程" + ActivitProccessEnum.getName(i)).put("data", i);
    }

    /**
     * @Date: 15:39 2017/6/16
     * 根据历史流程实例Id获取进度追踪图
     */
    @PostMapping(value = "/getHisProgressImg")
    @ResponseBody
    public R getHisProgressImg(@RequestParam("processId") String processInstanceId) throws UnsupportedEncodingException {

        String imgStr = respositoryService.getProgressImg(processInstanceId);
        try {

            if(StringUtils.isNotEmpty(imgStr)){
                return R.ok().put("data", imgStr);
            }else{
                return R.error("生成图片失败!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("生成图片失败!" + e.getMessage());
        }
    }


    @PostMapping(value = "/test")
    @ResponseBody
    public R test(){
        Sort sort = new Sort(Sort.Direction.DESC, "time");
        Pageable pageable = new PageRequest(0, 10, sort);


        Page<CompleteTask> byUserId = completeTaskReposirory.findByUserId("e5ec25b4-4643-453e-82d9-4fafd8288891", pageable);


        return R.ok().put("data",byUserId);
    }
}